import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
//线程池
class MyThreadPool {
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
    private int maxPoolSize = 0;
    private List<Thread > threadList = new ArrayList<>();
    //初始化线程池
    MyThreadPool(int corePoolSize, int  maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
        for(int i = 0;i < corePoolSize;i++) {
            Thread t = new Thread(() -> {
                try {
                    while(true) {
                        Runnable runnable = queue.take();
                        runnable.run();
                    }
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
            threadList.add(t);
        }
    }

    //将任务添加到线程池
    void submit(Runnable runnable) throws InterruptedException {
        //判断队列长度
        queue.put(runnable);

        if(queue.size() >= 500 && threadList.size() < maxPoolSize) {
            Thread t = new Thread(() -> {
                try {
                    while(true) {
                        Runnable task = queue.take();
                        task.run();
                    }
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }
}
//自我实现线程池
public class Demo {
    public static void main(String[] args) throws InterruptedException {
       MyThreadPool myThreadPool = new MyThreadPool(10,10);
       for (int i = 0;i < 10000;i++) {
           int id = i;
           myThreadPool.submit(new Runnable() {
               @Override
               public void run() {
                   System.out.println("hello " + id + Thread.currentThread().getName());
               }
           });
       }
    }
}